package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"GameServer/Game/sp"
	"sort"

	log "github.com/sirupsen/logrus"
)

// 获取当前圣诞活动，如果有多个活动存在，只返回一个活动
func GetCurrentChristmasActivity() (activ data.ActActivity, err error) {
	nowUnix := utils.TNow().Unix()
	tplLst, ok := data.Filters("ActActivities", func(val interface{}) bool {
		valT := val.(data.ActActivity)
		actTyp := int64(valT.ActTyp)
		beginTime, _ := utils.LayoutToTime(valT.BeginTime)
		endTime, _ := utils.LayoutToTime(valT.EndTime)
		return actTyp == data.ActivityEnum.Christmas && beginTime.Unix() <= nowUnix && nowUnix <= endTime.Unix()
	})

	if !ok || len(tplLst) == 0 {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到激活活动配置,ActActivities,或者没有圣诞活动")
		return
	}

	activ = tplLst[0].(data.ActActivity)
	return
}

// 获取模板奖励
func GetChristmasTreeAll() (tplLstT []data.ChristmasTree, err error) {
	// 获取圣诞树的信息
	tplLst, ok := data.GetAllDatas("ChristmasTrees")
	if !ok || len(tplLst) == 0 {
		log.WithFields(log.Fields{
			"method": "GetChristmasTree",
		}).Error("Christmas，没有ChristmasTrees配表，或者没有数据")
		return
	}
	tplLstT = make([]data.ChristmasTree, 0)
	for _, item := range tplLst {
		itemT := item.(data.ChristmasTree)
		tplLstT = append(tplLstT, itemT)
	}
	// 按照圣诞树的等级排序
	sort.Slice(tplLstT, func(i, j int) bool {
		return tplLstT[i].Id < tplLstT[j].Id
	})
	return
}

// 获取用户圣诞树信息
func GetChristmasTree(us *m.User) (uChristmasTree *m.UserChristmasTree) {
	uChristmasTree = m.GetUserChristmasTree(us.Uid.Hex())
	nowUnix := utils.TNow().Unix()
	// 活动正在进行，不用做处理
	if uChristmasTree.BeginTime <= nowUnix && nowUnix <= uChristmasTree.EndTime {
		return
	}
	// 活动结束，查看是否有活动开启
	activ, err := GetCurrentChristmasActivity()
	if err != nil {
		return
	}
	tplLst, err := GetChristmasTreeAll()
	if err != nil {
		return
	}
	bTime, _ := utils.LayoutToTime(activ.BeginTime)
	eTime, _ := utils.LayoutToTime(activ.EndTime)

	uChristmasTree.ActivId = int64(activ.ActivId)
	uChristmasTree.BeginTime = bTime.Unix()
	uChristmasTree.EndTime = eTime.Unix()
	uChristmasTree.Level = 1
	// 初始化玩家的圣诞树阈值
	for _, item := range tplLst {
		id := int64(item.Id)
		ball := int64(item.Ball)
		candy := int64(item.Candy)
		stocking := int64(item.Stocking)

		if uChristmasTree.MaxLevel < id {
			uChristmasTree.MaxLevel = id
		}

		uChristmasTree.Tree[id] = &m.ChristmasTree{
			Level:    id,
			Ball:     ball,
			Candy:    candy,
			Stocking: stocking,
		}
	}

	uChristmasTree.Update(uChristmasTree)
	return
}

// 给用户的圣诞树添加道具
func AddGoodChristmasTree(us *m.User, typ int64, val int64, PSend func(interface{}) error) {
	uChristmasTree := m.GetUserChristmasTree(us.Uid.Hex())
	switch typ {
	case data.GoodsTypeEnum.ChristmasBall:
		uChristmasTree.Ball += val
	case data.GoodsTypeEnum.ChristmasCandy:
		uChristmasTree.Candy += val
	case data.GoodsTypeEnum.ChristmasStocking:
		uChristmasTree.Stocking += val
	default:
		return
	}
	flag := false
	if val, ok := uChristmasTree.Tree[uChristmasTree.Level]; ok {
		if val.Ball <= uChristmasTree.Ball && val.Candy <= uChristmasTree.Candy && val.Stocking <= uChristmasTree.Stocking && val.State == 0 {
			// 该等级的圣诞树道具达到要求，并且状态为0。将状态改为完成
			val.State = 1
			flag = true
		}
	}
	if flag {
		uChristmasTree.Update(uChristmasTree)
		// 通知客户端有圣诞任务完成
		PSend(&sp.ChristmasNoticeRequest{})
	}
}

// 领取圣诞树的奖励
func GetChristmasReward(from string, us *m.User, level int64, PSend func(interface{}) error) (uChristmasTree *m.UserChristmasTree, uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, err error) {
	uChristmasTree = m.GetUserChristmasTree(us.Uid.Hex())
	val, ok := uChristmasTree.Tree[level]
	if !ok {
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"level":  level,
			"method": "GetChristmasReward",
		}).Error("圣诞树没有该等级的奖励")
		err = errors.NewErrcode(data.Errcode.ServerErr, "圣诞树没有该等级的奖励")
		return
	}
	if val.State != 1 {
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"state":  val.State,
			"method": "GetChristmasReward",
		}).Error("该等级的圣诞树的状态没有完成或者奖励已经领取")
		err = errors.NewErrcode(data.Errcode.ServerErr, "圣诞树没有该等级的奖励")
		return
	}
	// 圣诞树，该等级状态为1，已完成。
	// 领取该等级的道具
	tpl, ok := data.Get("ChristmasTrees", uint64(level))
	if !ok {
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"level":  level,
			"method": "GetChristmasReward",
		}).Error("没有ChristmasTrees配表，或者没有该等级的奖励")
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有ChristmasTree配表，或者没有该等级的奖励")
		return
	}
	tplT := tpl.(data.ChristmasTree)
	giveGoods := make([]m.BaseKV, 0)
	for _, item := range tplT.Reward {
		giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: int64(item.Value)})
	}
	// 给用户道具
	uProp, resGoods, boxResList, err = GiveGoodsByKvList(from, us, giveGoods, PSend)
	if err != nil {
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"method": "GetChristmasReward",
		}).Error("圣诞树给道具失败")
		return
	}
	// 给道具成功，将该等级的状态修改为领取
	val.State = 2
	// 领取道具，扣掉捡到的道具
	uChristmasTree.Ball -= val.Ball
	uChristmasTree.Candy -= val.Candy
	uChristmasTree.Stocking -= val.Stocking
	// 提升圣诞树的等级
	uChristmasTree.Level++
	if uChristmasTree.Level > uChristmasTree.MaxLevel {
		// 当圣诞树等级达到最大级，循环最后一个等级。
		uChristmasTree.Level = uChristmasTree.MaxLevel
		val.State = 0
	}
	// 扣掉道具，任然可以领取奖励，将状态改为1，可领取。
	val, _ = uChristmasTree.Tree[uChristmasTree.Level]
	if val.Ball <= uChristmasTree.Ball && val.Candy <= uChristmasTree.Candy && val.Stocking <= uChristmasTree.Stocking && val.State == 0 {
		// 该等级的圣诞树道具达到要求，并且状态为0。将状态改为完成
		val.State = 1
	}
	uChristmasTree.Update(uChristmasTree)
	return
}
